//
//  HJActivityIndicatorView.m
//  KaiChat
//
//  Created by lx on 2023/10/28.
//

#import "HJActivityIndicatorView.h"


@interface HJActivityIndicatorView()

@property (nonatomic, weak) UIImageView *imageView;
@property (nonatomic, weak) UIView *contentView;
@property (nonatomic, assign, getter=isAnimating) BOOL animating;
@property (nonatomic, strong) CABasicAnimation *rotationAnimation;

@end


@implementation HJActivityIndicatorView


- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        self.hidden = YES;
        self.animating = NO;
 
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.image = [UIImage imageNamed:@"sendMessageLoading"];
        self.imageView = imageView;
        [self addSubview:imageView];

    }
    return self;
}
 
- (void)layoutSubviews {
    [super layoutSubviews];
    _imageView.frame = self.bounds;
}

- (void)startAnimating {
    
    self.hidden = NO;

    if (self.animating) return;
    self.animating = YES;
 
    if ([self.imageView.layer.animationKeys containsObject:@"rotation"]) {
        [self.imageView.layer removeAnimationForKey:@"rotation"];
    }
 
    [self.imageView.layer addAnimation:self.rotationAnimation forKey:@"rotation"];
}

- (CABasicAnimation *)rotationAnimation {
    if (!_rotationAnimation) {
        _rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        _rotationAnimation.toValue = [NSNumber numberWithFloat:2 * M_PI];
        _rotationAnimation.duration = 0.6;
        _rotationAnimation.repeatCount = CGFLOAT_MAX;
        _rotationAnimation.removedOnCompletion = NO;
    }
    return _rotationAnimation;
}

- (void)stopAnimating {
    self.hidden = YES;
    if (!self.animating) return;
    self.animating = NO;
    if ([self.imageView.layer.animationKeys containsObject:@"rotation"]) {
        [self.imageView.layer removeAnimationForKey:@"rotation"];
    }
}

- (void)reset {
    self.animating = NO;
}

- (CGSize)intrinsicContentSize {
    return CGSizeMake(16, 16);
}


@end
